﻿Ext.define("CRM8000.Invertory.InitInvEditForm", {
    extend: "Ext.window.Window",

    config: {
        warehouse: null
    },

    initComponent: function () {
        var me = this;
        var warehouse = me.getWarehouse();

        Ext.define("CRM8000GoodsCategory", {
            extend: "Ext.data.Model",
            fields: ["id", "name"]
        });
        var storeGoodsCategory = Ext.create("Ext.data.Store", {
            autoLoad: false,
            model: "CRM8000GoodsCategory",
            data: []
        });
        me.storeGoodsCategory = storeGoodsCategory;

        Ext.apply(me, {
            title: "库存建账",
            modal: true,
            onEsc: Ext.emptyFn,
            width: 1000,
            height: 600,
            maximized: true,
            layout: "fit",
            items: [
                {
                    id: "editForm",
                    layout: "border",
                    border: 0,
                    bodyPadding: 5,
                    items: [{
                        xtype: "container", region: "north", height: 40,
                        html: "<h2>建账仓库：<span style='color:red'>" + warehouse.get("name") + "</span></h2>"
                    }, {
                        xtype: "panel", region: "center", layout: "border", border: 0,
                        items: [{
                            xtype: "panel", region: "center", layout: "border", border: 0,
                            items: [{
                                xtype: "panel", region: "north", height: 30,
                                layout: "hbox", border: 0,
                                items: [{ xtype: "displayfield", value: "商品分类" }, {
                                    id: "comboboxGoodsCategory",
                                    xtype: "combobox", flex: 1, store: storeGoodsCategory,
                                    editable: false, displayField: "name", valueField: "id",
                                    queryMode: "local",
                                    listeners: {
                                        change: function () { me.getGoods(); }
                                    }
                                }]
                            }, {
                                xtype: "panel", region: "center",
                                layout: "fit",
                                items: [this.getGoodsGrid()]
                            }]
                        }, {
                            title: "编辑区", xtype: "panel", region: "east", width: 400, split: true, collapsible: true,
                            items: [{
                                xtype: "form",
                                layout: "form",
                                border: 0,
                                fieldDefaults: {
                                    labelWidth: 60,
                                    labelAlign: "right",
                                    labelSeparator: "",
                                    msgTarget: 'side'
                                },
                                bodyPadding: 5,
                                defaultType: 'textfield',
                                items: [{
                                    id: "editGoodsCode",
                                    fieldLabel: "商品编码",
                                    xtype: "displayfield"
                                }, {
                                    id: "editGoodsName",
                                    fieldLabel: "品名",
                                    xtype: "displayfield"
                                }, {
                                    id: "editGoodsSpec",
                                    fieldLabel: "规格型号",
                                    xtype: "displayfield"
                                }, {
                                    id: "editGoodsCount",
                                    fieldLabel: "期初数量",
                                    width: "100%",
                                    xtype: "numberfield",
                                    allowDecimals: false,
                                    hideTrigger: true,
                                    beforeLabelTextTpl: CRM8000.Const.REQUIRED
                                }, {
                                    id: "editGoodsMoney",
                                    fieldLabel: "期初金额",
                                    xtype: "numberfield",
                                    allowDecimals: false,
                                    hideTrigger: true,
                                    beforeLabelTextTpl: CRM8000.Const.REQUIRED
                                }, {
                                    id: "editGoodsPrice",
                                    fieldLabel: "期初单价",
                                    xtype: "displayfield"
                                }]
                            }, {
                                xtype: "container",
                                layout: "hbox",
                                items: [{ xtype: "container", flex: 1 }, {
                                    id: "buttonSubmit",
                                    xtype: "button", text: "保存当前商品的建账信息", iconCls: "CRM8000-button-ok", flex: 2,
                                    handler: me.onSave, scope: me
                                }, { xtype: "container", flex: 1 }]
                            }]
                        }
                        ]
                    }
                    ]
                }
            ],
            buttons: [{ 
            	text: "关闭", handler: function () { me.close(); }
            }]
        });


        me.callParent(arguments);

        Ext.getCmp("editGoodsCount").on("specialkey", function (field, e) {
            if (e.getKey() == e.ENTER) {
                Ext.getCmp("editGoodsMoney").focus();
            }
        });
        Ext.getCmp("editGoodsMoney").on("specialkey", function (field, e) {
            if (e.getKey() == e.ENTER) {
                Ext.getCmp("buttonSubmit").focus();
            }
        });

        me.getGoodsCategories();
    },

    getGoodsGrid: function () {
        var me = this;
        if (me.__gridGoods) {
            return me.__gridGoods;
        }

        Ext.define("CRM8000InitInvGoods", {
            extend: "Ext.data.Model",
            fields: ["id", "goodsCode", "goodsName", "goodsSpec", "goodsCount", "unitName", "goodsMoney", "goodsPrice", "initDate"]
        });
        var storePWBill = Ext.create("Ext.data.Store", {
            autoLoad: false,
            model: "CRM8000InitInvGoods",
            data: []
        });

        me.__gridGoods = Ext.create("Ext.grid.Panel", {
            border: 0,
            columns: [
                { header: "商品编码", dataIndex: "goodsCode", menuDisabled: true, sortable: false, width: 80 },
                { header: "品名", dataIndex: "goodsName", menuDisabled: true, sortable: false, width: 200 },
                { header: "规格型号", dataIndex: "goodsSpec", menuDisabled: true, sortable: false, width: 200 },
                { header: "期初数量", dataIndex: "goodsCount", menuDisabled: true, sortable: false, align: "right" },
                { header: "单位", dataIndex: "unitName", menuDisabled: true, sortable: false, width: 50 },
                { header: "期初金额", dataIndex: "goodsMoney", menuDisabled: true, sortable: false, align: "right", xtype: "numbercolumn" },
                { header: "期初单价", dataIndex: "goodsPrice", menuDisabled: true, sortable: false, align: "right", xtype: "numbercolumn" }
            ],
            store: storePWBill,
            listeners: {
                select: {
                    fn: me.onGoodsGridSelect,
                    scope: me
                }
            }
        });


        return me.__gridGoods;
    },

    getGoodsCategories: function () {
        var store = this.storeGoodsCategory;

        var el = Ext.getBody();
        el.mask(CRM8000.Const.LOADING);
        Ext.Ajax.request({
            url: CRM8000.Const.BASE_URL + "initInvertory/goodsCategoryList",
            method: "POST",
            callback: function (options, success, response) {
                store.removeAll();

                if (success) {
                    var data = Ext.JSON.decode(response.responseText);
                    store.add(data);
                }

                el.unmask();
            }
        });
    },

    getGoods: function () {
        var comboboxGoodsCategory = Ext.getCmp("comboboxGoodsCategory");
        var gcId = comboboxGoodsCategory.getValue();
        var warehouseId = this.getWarehouse().get("id");
        var grid = this.getGoodsGrid();

        var el = grid.getEl();
        el.mask(CRM8000.Const.LOADING);
        Ext.Ajax.request({
            url: CRM8000.Const.BASE_URL + "initInvertory/goodsList",
            params: { categoryId: gcId, warehouseId: warehouseId },
            method: "POST",
            callback: function (options, success, response) {
                var store = grid.getStore();

                store.removeAll();

                if (success) {
                    var data = Ext.JSON.decode(response.responseText);
                    store.add(data);

                    if (store.getCount() > 0) {
                        grid.getSelectionModel().select(0);
                    }
                }

                el.unmask();
            }
        });
    },

    onGoodsGridSelect: function () {
        var me = this;
        var grid = me.getGoodsGrid();

        var item = grid.getSelectionModel().getSelection();
        if (item == null || item.length != 1) {
            return;
        }

        var goods = item[0];
        Ext.getCmp("editGoodsCode").setValue(goods.get("goodsCode"));
        Ext.getCmp("editGoodsName").setValue(goods.get("goodsName"));
        Ext.getCmp("editGoodsSpec").setValue(goods.get("goodsSpec"));
        var goodsCount = goods.get("goodsCount");
        if (goodsCount == "0") {
            Ext.getCmp("editGoodsCount").setValue(null);
            Ext.getCmp("editGoodsMoney").setValue(null);
            Ext.getCmp("editGoodsPrice").setValue(null);
        } else {
            Ext.getCmp("editGoodsCount").setValue(goods.get("goodsCount"));
            Ext.getCmp("editGoodsMoney").setValue(goods.get("goodsMoney"));
            Ext.getCmp("editGoodsPrice").setValue(goods.get("goodsPrice"));
        }
    },

    updateAfterSave: function(goods) {
    	goods.set("goodsCount", Ext.getCmp("editGoodsCount").getValue());
    	goods.set("goodsMoney", Ext.getCmp("editGoodsMoney").getValue());

    	var p = Ext.getCmp("editGoodsMoney").getValue() / Ext.getCmp("editGoodsCount").getValue();
    	p = Ext.Number.toFixed(p, 2);
    	goods.set("goodsPrice", p);
    
    	this.getGoodsGrid().getStore().commitChanges();
    },
    
    onSave: function () {
        var me = this;

        var grid = me.getGoodsGrid();
        var item = grid.getSelectionModel().getSelection();
        if (item == null || item.length != 1) {
            CRM8000.MsgBox.showInfo("请选择一个建账商品");

            return;
        }

        var goods = item[0];

        var goodsCount = Ext.getCmp("editGoodsCount").getValue();
        var goodsMoney = Ext.getCmp("editGoodsMoney").getValue();

        var el = Ext.getBody();
        el.mask(CRM8000.Const.SAVING)

        Ext.Ajax.request({
            url: CRM8000.Const.BASE_URL + "initInvertory/commitInitInvertoryGoods",
            params: {
                goodsId: goods.get("id"),
                goodsCount: goodsCount,
                goodsMoney: goodsMoney,
                warehouseId: me.getWarehouse().get("id")
            },
            method: "POST",
            callback: function (options, success, response) {
                el.unmask();

                if (success) {
                    var result = Ext.JSON.decode(response.responseText);

                    if (result.success) {
                    	me.updateAfterSave(goods);
                        grid.getSelectionModel().selectNext();
                    } else {
                        CRM8000.MsgBox.showInfo(result.msg, function () {
                            Ext.getCmp("editGoodsCount").focus();
                        });
                    }
                }
            }
        });
    }
});